package com.elite.groovy.callback
import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.alibaba.fastjson.JSONArray

import com.wisdge.utils.StringUtils
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import org.springframework.util.Base64Utils
import org.springframework.util.DigestUtils
import net.sf.json.JSONObject;
import javax.crypto.Cipher
import javax.crypto.spec.SecretKeySpec
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiTPRJPushList* @Description:泰迪熊 名单推送* @remak ：推送已经下达坐席的名单客户信息加密处理* @author: luo* @date 2023-02-06 11:11:00
 *
 */

public class apiTPRJPushList1 implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiTPRJPushList1.class);
    public static long TimeMillis = System.currentTimeMillis();
    /**
     * 编码
     */
    private static final String ENCODING = "UTF-8";
    /**
     * 算法定义
     */
    private static final String AES_ALGORITHM = "AES";
    /**
     * 指定填充方式
     */
    private static final String CIPHER_PADDING = "AES/ECB/PKCS5Padding";


    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");

        JSONObject result = new JSONObject();
        // 获取数据源List<Map<String, Object>>
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());


        try {
            String selectSQL = "Select ob.objective_Guid,\n" +
                    "       s.staff_id,\n" +
                    "       c.Customername || ',' || ob.objective_Guid,\n" +
                    "       case\n" +
                    "         when c.Mobile is not null then\n" +
                    "          c.Mobile\n" +
                    "         when c.tel_1 is not null then\n" +
                    "          c.tel_1\n" +
                    "         when c.atel_1 is not null then\n" +
                    "          c.atel_1\n" +
                    "         when c.atel_2 is not null then\n" +
                    "          c.atel_2\n" +
                    "         when c.atel_3 is not null then\n" +
                    "          c.atel_3\n" +
                    "         when c.Atel_4 is not null then\n" +
                    "          c.atel_4\n" +
                    "       end as mobile,\n" +
                    "       s.staffname,\n" +
                    "       s.stringfield4,\n" +
                    "       case\n" +
                    "         when ob.attempt = 0 then\n" +
                    "          '首拨任务'\n" +
                    "         when ob.expectstarttime is not null and ob.attempt != 0 then\n" +
                    "          '预约任务'\n" +
                    "       end as taskname,\n" +
                    "       to_char(sysdate, 'yyyymmdd') as datetime\n" +
                    "  From elitetask ob\n" +
                    "  Left Join Customer T2\n" +
                    "    On ob.Customer_Guid = T2.Customer_Guid\n" +
                    "  Left Join Customer c\n" +
                    "    On c.Customer_Guid = T2.Parent_Guid\n" +
                    "  Left Join staff s\n" +
                    "    On s.staff_id = ob.handleby_id\n" +
                    "  Left Join rolegroup r\n" +
                    "    On r.rolegroup_id = ob.handlegroup_id\n" +
                    " Where ob.obflag = 1\n" +
                    "   and ob.handleby_id is not null\n" +
                    "   and s.stringfield3 = '1'\n" +
                    "   And ob.Createddate > Add_Months(Sysdate, -6)\n" +
                    "   and ob.objective_guid not in\n" +
                    "       (select tp.objective_guid\n" +
                    "          from Tprj_PushList tp\n" +
                    "          left join Tprj_PushList_his tph\n" +
                    "            on tp.rec_guid = tph.rec_guid\n" +
                    "         where trunc(tp.createddate) = trunc(sysdate))\n";
            List<Map<String, Object>> selectExits = jt.queryForList(selectSQL);
            String name = "";
            JSONObject createbody = new JSONObject();
            JSONObject obj = new JSONObject();
            JSONArray agentJids = new JSONArray()
            JSONArray customers = new JSONArray();
            JSONObject jb = new JSONObject();

            String str = String.valueOf(TimeMillis);
            String IV_SEED = DigestUtils.md5DigestAsHex(str.getBytes());

            if (selectExits.size() > 0) {
                for (int i; i < selectExits.size(); i++) {
                    Map selectExitsm = selectExits.get(i);
                    String datetime = selectExitsm.get("datetime");
                    String taskname = selectExitsm.get("taskname");
                    String staffname = selectExitsm.get("staffname");
                    String workgroupJid = selectExitsm.get("stringfield4");
                    String staff_id = selectExitsm.get("staff_id")

                    if (taskname == "首拨任务") {
                        push_create(obj, createbody, customers, agentJids, staffname, datetime, taskname, workgroupJid, jt, jb, selectExitsm, IV_SEED);
                    } else if (taskname == "预约任务") {
                        push_create(obj, createbody, customers, agentJids, staffname, datetime, taskname, workgroupJid, jt, jb, selectExitsm, IV_SEED);
                    }
                }

                result.put("code", jb.getString("code"));
                result.put("msg", jb.getString("message"));
            } else {
                result.put("code", 1);
                result.put("msg", "无可推送名单");
            }

        } catch (Exception e) {
            log.error("接口处理异常", e);
            result.put("code", -1);
            result.put("msg", e.getMessage());
            result.put("data", "");
        }

        log.debug("推送名单处理完成返回结果:" + result.toString());

        return result.toString();
    }

    public static void push_create(JSONObject obj, JSONObject createbody, JSONArray customers, JSONArray agentJids, String staffname, String datetime, String taskname, String workgroupJid, JdbcTemplate jt, JSONObject jb, Map selectExitsm, String IV_SEED) {
        String token = token(jt);
        Map<String, String> TokenParams = new HashMap<String, String>();
        TokenParams.put("X-Token", token);
        TokenParams.put("Content-Type", "application/json");

        String sql = "select s.target_url from sys_interface_config s where status=1 and type='tprj.create'";
        List<Map<String, Object>> createlist = jt.queryForList(sql)
        obj.put("name", encrypt(selectExitsm.get("customername").toString(), IV_SEED.substring(8, 24)));
        obj.put("phone", encrypt(selectExitsm.get("mobile").toString(), IV_SEED.substring(8, 24)));

        if (agentJids.indexOf(staffname) == -1) {
            agentJids.add(staffname);
        }
        customers.add(obj);
        createbody.put("name", datetime + taskname + staffname)
        createbody.put("description", "自动任务")
        createbody.put("accessNumber", "")
        createbody.put("sceneId", "")
        createbody.put("workgroupJid", workgroupJid)
        createbody.put("agentJids", agentJids)
        createbody.put("customers", customers)

        log.debug("泰迪熊请求参数：" + createbody.toString());

        if (createlist) {

            Map createmap = createlist.get(0)
            String create_url = createmap.get("target_url");

            String create_result = Util.doHttpPostUseHead(create_url, createbody.toString(), "UTF-8", 5000, 0, TokenParams)
            jb = JSONObject.fromObject(create_result)

            log.debug("泰迪熊返回参数：" + jb.toString());
            String sql1 = "insert into qt_dm_ifc_log_new(id,offer_no,ifc_no,send_info,return_info,send_time,return_time) values(sys_guid()," + jb.getString("taskId") + ",'TPRJ1'," + createbody.toString() + "," + jb.toString() + ",sysdate," + jb.getString("timestamp") + ")"

            jt.update(sql1);

            String s = selectExitsm.get("customername").toString();
            int c = s.indexOf(",");
            String objective_guid = s.substring(c + 1, s.length());

            String customername = s.substring(0, c);

            if (jb.getString("code") == "200") {
                String pushlisthis = "insert into Tprj_PushList_his(REC_GUID,CREATEDDATE,TASKID,TASKNAME,CUSTOMERNAME,MOBILE,STAFF_ID,QUEUE,OBJECTIVE_GUID) values(sys_guid(),sysdate," + jb.getString('taskId') + "," + taskname + "," + customername + "," + selectExitsm.get('mobile') + "," + selectExitsm.get("staff_id") + ",''," + objective_guid + ")";

                jt.update(pushlisthis);
            } else {
                String pushlist = "insert into Tprj_PushList(REC_GUID,CREATEDDATE,TASKID,TASKNAME,CUSTOMERNAME,MOBILE,STAFF_ID,QUEUE,OBJECTIVE_GUID) values(sys_guid(),sysdate," + jb.getString('taskId') + "," + taskname + "," + customername + "," + selectExitsm.get('mobile') + "," + selectExitsm.get("staff_id") + ",''," + objective_guid + ")"

                jt.update(pushlist);
            }
        }

    }


/**
 *  加密
 *
 * @param content 待加密内容
 * @param aesKey 密码
 * @return
 */
    public static String encrypt(String content, String aesKey) {
        if (StringUtils.isBlank(content)) {
            log.info("AES encrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if (StringUtils.isNotBlank(aesKey) && aesKey.length() == 16) {
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(ENCODING);
                //设置加密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
                //选择加密
                cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
                //根据待加密内容生成字节数组
                byte[] encrypted = cipher.doFinal(content.getBytes(ENCODING));
                //返回base64字符串
                return Base64Utils.encodeToString(encrypted);
            } catch (Exception e) {
                log.info("AES encrypt exception:" + e.getMessage());
                throw new RuntimeException(e);
            }

        } else {
            log.info("AES encrypt: the aesKey is null or error!");
            return null;
        }
    }
/**
 * 解密
 *
 * @param content 待解密内容
 * @param aesKey 密码
 * @return
 */
    public static String decrypt(String content, String aesKey) {
        if (StringUtils.isBlank(content)) {
            log.info("AES decrypt: the content is null!");
            return null;
        }
        //判断秘钥是否为16位
        if (StringUtils.isNotBlank(aesKey) && aesKey.length() == 16) {
            try {
                //对密码进行编码
                byte[] bytes = aesKey.getBytes(ENCODING);
                //设置解密算法，生成秘钥
                SecretKeySpec skeySpec = new SecretKeySpec(bytes, AES_ALGORITHM);
                // "算法/模式/补码方式"
                Cipher cipher = Cipher.getInstance(CIPHER_PADDING);
                //选择解密
                cipher.init(Cipher.DECRYPT_MODE, skeySpec);

                //先进行Base64解码
                byte[] decodeBase64 = Base64Utils.decodeFromString(content);

                //根据待解密内容进行解密
                byte[] decrypted = cipher.doFinal(decodeBase64);
                //将字节数组转成字符串
                return new String(decrypted, ENCODING);
            } catch (Exception e) {
                log.info("AES decrypt exception:" + e.getMessage());
                throw new RuntimeException(e);
            }

        } else {
            log.info("AES decrypt: the aesKey is null or error!");
            return null;
        }
    }

/**
 token 处理
 */

    public String token(JdbcTemplate jt) {
        String token = "";
        String s = "select s.target_url from sys_interface_config s where status=1 and type='tprj.token'";
        List<Map<String, Object>> li = jt.queryForList(s);
        if (li.size() > 0) {
            Map selecttoekn = li.get(0)
            String token_url = selecttoekn.get("target_url");

            String tokenresult = Util.doHttpGet(token_url, "UTF-8", 5000, 0)
            JSONObject tokenjson = JSONObject.fromObject(tokenresult)

            if (tokenjson.getInteger("code") == 200) {
                token = tokenjson.getString("token")

            }
        }
        return token;
    }

}
